{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# SELECT within SELECT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "-- \u001b[1mAttaching packages\u001b[22m --------------------------------------- tidyverse 1.3.0 --\n",
      "\n",
      "\u001b[32mv\u001b[39m \u001b[34mggplot2\u001b[39m 3.3.0     \u001b[32mv\u001b[39m \u001b[34mpurrr  \u001b[39m 0.3.4\n",
      "\u001b[32mv\u001b[39m \u001b[34mtibble \u001b[39m 3.0.1     \u001b[32mv\u001b[39m \u001b[34mdplyr  \u001b[39m 0.8.5\n",
      "\u001b[32mv\u001b[39m \u001b[34mtidyr  \u001b[39m 1.0.2     \u001b[32mv\u001b[39m \u001b[34mstringr\u001b[39m 1.4.0\n",
      "\u001b[32mv\u001b[39m \u001b[34mreadr  \u001b[39m 1.3.1     \u001b[32mv\u001b[39m \u001b[34mforcats\u001b[39m 0.5.0\n",
      "\n",
      "-- \u001b[1mConflicts\u001b[22m ------------------------------------------ tidyverse_conflicts() --\n",
      "\u001b[31mx\u001b[39m \u001b[34mdplyr\u001b[39m::\u001b[32mfilter()\u001b[39m masks \u001b[34mstats\u001b[39m::filter()\n",
      "\u001b[31mx\u001b[39m \u001b[34mdplyr\u001b[39m::\u001b[32mlag()\u001b[39m    masks \u001b[34mstats\u001b[39m::lag()\n",
      "\n"
     ]
    },
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Password? ·········\n"
     ]
    }
   ],
   "source": [
    "library(tidyverse)\n",
    "library(DBI)\n",
    "library(getPass)\n",
    "drv <- switch(Sys.info()['sysname'],\n",
    "             Windows=\"PostgreSQL Unicode(x64)\",\n",
    "             Darwin=\"/usr/local/lib/psqlodbcw.so\",\n",
    "             Linux=\"PostgreSQL\")\n",
    "con <- dbConnect(\n",
    "  odbc::odbc(),\n",
    "  driver = drv,\n",
    "  Server = \"localhost\",\n",
    "  Database = \"sqlzoo\",\n",
    "  UID = \"postgres\",\n",
    "  PWD = getPass(\"Password?\"),\n",
    "  Port = 5432\n",
    ")\n",
    "options(repr.matrix.max.rows=20)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Bigger than Russia\n",
    "\n",
    "**List each country name where the population is larger than that of 'Russia'.**\n",
    "\n",
    "```\n",
    "world(name, continent, area, population, gdp)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "world <- dbReadTable(con, 'world')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 8 × 1</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Bangladesh   </td></tr>\n",
       "\t<tr><td>Brazil       </td></tr>\n",
       "\t<tr><td>China        </td></tr>\n",
       "\t<tr><td>India        </td></tr>\n",
       "\t<tr><td>Indonesia    </td></tr>\n",
       "\t<tr><td>Nigeria      </td></tr>\n",
       "\t<tr><td>Pakistan     </td></tr>\n",
       "\t<tr><td>United States</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 8 × 1\n",
       "\\begin{tabular}{l}\n",
       " name\\\\\n",
       " <chr>\\\\\n",
       "\\hline\n",
       "\t Bangladesh   \\\\\n",
       "\t Brazil       \\\\\n",
       "\t China        \\\\\n",
       "\t India        \\\\\n",
       "\t Indonesia    \\\\\n",
       "\t Nigeria      \\\\\n",
       "\t Pakistan     \\\\\n",
       "\t United States\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 8 × 1\n",
       "\n",
       "| name &lt;chr&gt; |\n",
       "|---|\n",
       "| Bangladesh    |\n",
       "| Brazil        |\n",
       "| China         |\n",
       "| India         |\n",
       "| Indonesia     |\n",
       "| Nigeria       |\n",
       "| Pakistan      |\n",
       "| United States |\n",
       "\n"
      ],
      "text/plain": [
       "  name         \n",
       "1 Bangladesh   \n",
       "2 Brazil       \n",
       "3 China        \n",
       "4 India        \n",
       "5 Indonesia    \n",
       "6 Nigeria      \n",
       "7 Pakistan     \n",
       "8 United States"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>% \n",
    "    filter(name=='Russia') %>% \n",
    "    select(population) %>% pull\n",
    "world %>%\n",
    "    filter(population > bm) %>% \n",
    "    select(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Richer than UK\n",
    "\n",
    "**Show the countries in Europe with a per capita GDP greater than 'United Kingdom'.**\n",
    "\n",
    "> _Per Capita GDP_   \n",
    "> The per capita GDP is the gdp/population"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 17 × 1</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Andorra      </td></tr>\n",
       "\t<tr><td>Austria      </td></tr>\n",
       "\t<tr><td>Belgium      </td></tr>\n",
       "\t<tr><td>Denmark      </td></tr>\n",
       "\t<tr><td>Finland      </td></tr>\n",
       "\t<tr><td>France       </td></tr>\n",
       "\t<tr><td>Germany      </td></tr>\n",
       "\t<tr><td>Iceland      </td></tr>\n",
       "\t<tr><td>Ireland      </td></tr>\n",
       "\t<tr><td>Liechtenstein</td></tr>\n",
       "\t<tr><td>Luxembourg   </td></tr>\n",
       "\t<tr><td>Monaco       </td></tr>\n",
       "\t<tr><td>Netherlands  </td></tr>\n",
       "\t<tr><td>Norway       </td></tr>\n",
       "\t<tr><td>San Marino   </td></tr>\n",
       "\t<tr><td>Sweden       </td></tr>\n",
       "\t<tr><td>Switzerland  </td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 17 × 1\n",
       "\\begin{tabular}{l}\n",
       " name\\\\\n",
       " <chr>\\\\\n",
       "\\hline\n",
       "\t Andorra      \\\\\n",
       "\t Austria      \\\\\n",
       "\t Belgium      \\\\\n",
       "\t Denmark      \\\\\n",
       "\t Finland      \\\\\n",
       "\t France       \\\\\n",
       "\t Germany      \\\\\n",
       "\t Iceland      \\\\\n",
       "\t Ireland      \\\\\n",
       "\t Liechtenstein\\\\\n",
       "\t Luxembourg   \\\\\n",
       "\t Monaco       \\\\\n",
       "\t Netherlands  \\\\\n",
       "\t Norway       \\\\\n",
       "\t San Marino   \\\\\n",
       "\t Sweden       \\\\\n",
       "\t Switzerland  \\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 17 × 1\n",
       "\n",
       "| name &lt;chr&gt; |\n",
       "|---|\n",
       "| Andorra       |\n",
       "| Austria       |\n",
       "| Belgium       |\n",
       "| Denmark       |\n",
       "| Finland       |\n",
       "| France        |\n",
       "| Germany       |\n",
       "| Iceland       |\n",
       "| Ireland       |\n",
       "| Liechtenstein |\n",
       "| Luxembourg    |\n",
       "| Monaco        |\n",
       "| Netherlands   |\n",
       "| Norway        |\n",
       "| San Marino    |\n",
       "| Sweden        |\n",
       "| Switzerland   |\n",
       "\n"
      ],
      "text/plain": [
       "   name         \n",
       "1  Andorra      \n",
       "2  Austria      \n",
       "3  Belgium      \n",
       "4  Denmark      \n",
       "5  Finland      \n",
       "6  France       \n",
       "7  Germany      \n",
       "8  Iceland      \n",
       "9  Ireland      \n",
       "10 Liechtenstein\n",
       "11 Luxembourg   \n",
       "12 Monaco       \n",
       "13 Netherlands  \n",
       "14 Norway       \n",
       "15 San Marino   \n",
       "16 Sweden       \n",
       "17 Switzerland  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>% \n",
    "    filter(name=='United Kingdom') %>% \n",
    "    mutate(pc_gdp=gdp/population) %>% \n",
    "    select(pc_gdp) %>% \n",
    "    pull\n",
    "world %>% \n",
    "    mutate(pc_gdp=gdp/population) %>% \n",
    "    filter(continent=='Europe' & pc_gdp > bm) %>%\n",
    "    select(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Neighbours of Argentina and Australia\n",
    "\n",
    "\n",
    "List the name and continent of countries in the continents containing either Argentina or Australia. Order by name of the country."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 27 × 2</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th><th scope=col>continent</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Argentina</td><td>South America</td></tr>\n",
       "\t<tr><td>Australia</td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Bolivia  </td><td>South America</td></tr>\n",
       "\t<tr><td>Brazil   </td><td>South America</td></tr>\n",
       "\t<tr><td>Chile    </td><td>South America</td></tr>\n",
       "\t<tr><td>Colombia </td><td>South America</td></tr>\n",
       "\t<tr><td>Ecuador  </td><td>South America</td></tr>\n",
       "\t<tr><td>Fiji     </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Guyana   </td><td>South America</td></tr>\n",
       "\t<tr><td>Kiribati </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>...</td><td>...</td></tr>\n",
       "\t<tr><td>Peru                            </td><td>South America</td></tr>\n",
       "\t<tr><td>Saint Vincent and the Grenadines</td><td>South America</td></tr>\n",
       "\t<tr><td>Samoa                           </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Solomon Islands                 </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Suriname                        </td><td>South America</td></tr>\n",
       "\t<tr><td>Tonga                           </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Tuvalu                          </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Uruguay                         </td><td>South America</td></tr>\n",
       "\t<tr><td>Vanuatu                         </td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Venezuela                       </td><td>South America</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 27 × 2\n",
       "\\begin{tabular}{ll}\n",
       " name & continent\\\\\n",
       " <chr> & <chr>\\\\\n",
       "\\hline\n",
       "\t Argentina & South America\\\\\n",
       "\t Australia & Oceania      \\\\\n",
       "\t Bolivia   & South America\\\\\n",
       "\t Brazil    & South America\\\\\n",
       "\t Chile     & South America\\\\\n",
       "\t Colombia  & South America\\\\\n",
       "\t Ecuador   & South America\\\\\n",
       "\t Fiji      & Oceania      \\\\\n",
       "\t Guyana    & South America\\\\\n",
       "\t Kiribati  & Oceania      \\\\\n",
       "\t ... & ...\\\\\n",
       "\t Peru                             & South America\\\\\n",
       "\t Saint Vincent and the Grenadines & South America\\\\\n",
       "\t Samoa                            & Oceania      \\\\\n",
       "\t Solomon Islands                  & Oceania      \\\\\n",
       "\t Suriname                         & South America\\\\\n",
       "\t Tonga                            & Oceania      \\\\\n",
       "\t Tuvalu                           & Oceania      \\\\\n",
       "\t Uruguay                          & South America\\\\\n",
       "\t Vanuatu                          & Oceania      \\\\\n",
       "\t Venezuela                        & South America\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 27 × 2\n",
       "\n",
       "| name &lt;chr&gt; | continent &lt;chr&gt; |\n",
       "|---|---|\n",
       "| Argentina | South America |\n",
       "| Australia | Oceania       |\n",
       "| Bolivia   | South America |\n",
       "| Brazil    | South America |\n",
       "| Chile     | South America |\n",
       "| Colombia  | South America |\n",
       "| Ecuador   | South America |\n",
       "| Fiji      | Oceania       |\n",
       "| Guyana    | South America |\n",
       "| Kiribati  | Oceania       |\n",
       "| ... | ... |\n",
       "| Peru                             | South America |\n",
       "| Saint Vincent and the Grenadines | South America |\n",
       "| Samoa                            | Oceania       |\n",
       "| Solomon Islands                  | Oceania       |\n",
       "| Suriname                         | South America |\n",
       "| Tonga                            | Oceania       |\n",
       "| Tuvalu                           | Oceania       |\n",
       "| Uruguay                          | South America |\n",
       "| Vanuatu                          | Oceania       |\n",
       "| Venezuela                        | South America |\n",
       "\n"
      ],
      "text/plain": [
       "    name                             continent    \n",
       "1   Argentina                        South America\n",
       "2   Australia                        Oceania      \n",
       "3   Bolivia                          South America\n",
       "4   Brazil                           South America\n",
       "5   Chile                            South America\n",
       "6   Colombia                         South America\n",
       "7   Ecuador                          South America\n",
       "8   Fiji                             Oceania      \n",
       "9   Guyana                           South America\n",
       "10  Kiribati                         Oceania      \n",
       "... ...                              ...          \n",
       "18  Peru                             South America\n",
       "19  Saint Vincent and the Grenadines South America\n",
       "20  Samoa                            Oceania      \n",
       "21  Solomon Islands                  Oceania      \n",
       "22  Suriname                         South America\n",
       "23  Tonga                            Oceania      \n",
       "24  Tuvalu                           Oceania      \n",
       "25  Uruguay                          South America\n",
       "26  Vanuatu                          Oceania      \n",
       "27  Venezuela                        South America"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>%\n",
    "    filter(name %in% c('Argentina', 'Australia')) %>% \n",
    "    select(continent) %>% \n",
    "    distinct %>% \n",
    "    pull\n",
    "world %>% \n",
    "    filter(continent %in% bm) %>%\n",
    "    arrange(name) %>% \n",
    "    select(name, continent)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Between Canada and Poland\n",
    "\n",
    "Which country has a population that is more than Canada but less than Poland? Show the name and the population."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 2 × 2</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th><th scope=col>population</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;dbl&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Iraq </td><td>36004552</td></tr>\n",
       "\t<tr><td>Sudan</td><td>37289406</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 2 × 2\n",
       "\\begin{tabular}{ll}\n",
       " name & population\\\\\n",
       " <chr> & <dbl>\\\\\n",
       "\\hline\n",
       "\t Iraq  & 36004552\\\\\n",
       "\t Sudan & 37289406\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 2 × 2\n",
       "\n",
       "| name &lt;chr&gt; | population &lt;dbl&gt; |\n",
       "|---|---|\n",
       "| Iraq  | 36004552 |\n",
       "| Sudan | 37289406 |\n",
       "\n"
      ],
      "text/plain": [
       "  name  population\n",
       "1 Iraq  36004552  \n",
       "2 Sudan 37289406  "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>% \n",
    "    filter(name %in% c('Canada', 'Poland')) %>% \n",
    "    select(population) %>% \n",
    "    pull %>%\n",
    "    set_names(c('Canada', 'Poland'))\n",
    "world %>% \n",
    "    filter(population > bm['Canada'] &\n",
    "           population < bm['Poland']) %>% \n",
    "    select(name, population)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Percentages of Germany\n",
    "\n",
    "Germany (population 80 million) has the largest population of the countries in Europe. Austria (population 8.5 million) has 11% of the population of Germany.\n",
    "\n",
    "**Show the name and the population of each country in Europe. Show the population as a percentage of the population of Germany.**\n",
    "\n",
    "The format should be Name, Percentage for example:\n",
    "\n",
    "name\t| percentage\n",
    "--------|-----------\n",
    "Albania\t| 3%\n",
    "Andorra\t| 0%\n",
    "Austria\t| 11%\n",
    "...\t| ...\n",
    "\n",
    "> _Decimal places_   \n",
    "> You can use the function ROUND to remove the decimal places.\n",
    "\n",
    "> _Percent symbol %_\n",
    "> You can use the function CONCAT to add the percentage symbol.\n",
    "\n",
    "[To get a well rounded view of the important features of SQL you should move on to the next tutorial concerning aggregates.](https://sqlzoo.net/wiki/SUM_and_COUNT)\n",
    "\n",
    "To gain an absurdly detailed view of one insignificant feature of the language, read on.\n",
    "\n",
    "We can use the word `ALL` to allow >= or > or < or <=to act over a list. For example, you can find the largest country in the world, by population with this query:\n",
    "\n",
    "```sql\n",
    "SELECT name\n",
    "  FROM world\n",
    " WHERE population >= ALL(SELECT population\n",
    "                           FROM world\n",
    "                          WHERE population>0)\n",
    "```\n",
    "\n",
    "You need the condition **population>0** in the sub-query as some countries have **null** for population."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 44 × 2</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th><th scope=col>percentage</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Albania               </td><td>3% </td></tr>\n",
       "\t<tr><td>Andorra               </td><td>0% </td></tr>\n",
       "\t<tr><td>Austria               </td><td>11%</td></tr>\n",
       "\t<tr><td>Belarus               </td><td>12%</td></tr>\n",
       "\t<tr><td>Belgium               </td><td>14%</td></tr>\n",
       "\t<tr><td>Bosnia and Herzegovina</td><td>5% </td></tr>\n",
       "\t<tr><td>Bulgaria              </td><td>9% </td></tr>\n",
       "\t<tr><td>Croatia               </td><td>5% </td></tr>\n",
       "\t<tr><td>Czech Republic        </td><td>13%</td></tr>\n",
       "\t<tr><td>Denmark               </td><td>7% </td></tr>\n",
       "\t<tr><td>...</td><td>...</td></tr>\n",
       "\t<tr><td>San Marino    </td><td>0% </td></tr>\n",
       "\t<tr><td>Serbia        </td><td>9% </td></tr>\n",
       "\t<tr><td>Slovakia      </td><td>7% </td></tr>\n",
       "\t<tr><td>Slovenia      </td><td>3% </td></tr>\n",
       "\t<tr><td>Spain         </td><td>58%</td></tr>\n",
       "\t<tr><td>Sweden        </td><td>12%</td></tr>\n",
       "\t<tr><td>Switzerland   </td><td>10%</td></tr>\n",
       "\t<tr><td>Ukraine       </td><td>53%</td></tr>\n",
       "\t<tr><td>United Kingdom</td><td>79%</td></tr>\n",
       "\t<tr><td>Vatican City  </td><td>0% </td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 44 × 2\n",
       "\\begin{tabular}{ll}\n",
       " name & percentage\\\\\n",
       " <chr> & <chr>\\\\\n",
       "\\hline\n",
       "\t Albania                & 3\\% \\\\\n",
       "\t Andorra                & 0\\% \\\\\n",
       "\t Austria                & 11\\%\\\\\n",
       "\t Belarus                & 12\\%\\\\\n",
       "\t Belgium                & 14\\%\\\\\n",
       "\t Bosnia and Herzegovina & 5\\% \\\\\n",
       "\t Bulgaria               & 9\\% \\\\\n",
       "\t Croatia                & 5\\% \\\\\n",
       "\t Czech Republic         & 13\\%\\\\\n",
       "\t Denmark                & 7\\% \\\\\n",
       "\t ... & ...\\\\\n",
       "\t San Marino     & 0\\% \\\\\n",
       "\t Serbia         & 9\\% \\\\\n",
       "\t Slovakia       & 7\\% \\\\\n",
       "\t Slovenia       & 3\\% \\\\\n",
       "\t Spain          & 58\\%\\\\\n",
       "\t Sweden         & 12\\%\\\\\n",
       "\t Switzerland    & 10\\%\\\\\n",
       "\t Ukraine        & 53\\%\\\\\n",
       "\t United Kingdom & 79\\%\\\\\n",
       "\t Vatican City   & 0\\% \\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 44 × 2\n",
       "\n",
       "| name &lt;chr&gt; | percentage &lt;chr&gt; |\n",
       "|---|---|\n",
       "| Albania                | 3%  |\n",
       "| Andorra                | 0%  |\n",
       "| Austria                | 11% |\n",
       "| Belarus                | 12% |\n",
       "| Belgium                | 14% |\n",
       "| Bosnia and Herzegovina | 5%  |\n",
       "| Bulgaria               | 9%  |\n",
       "| Croatia                | 5%  |\n",
       "| Czech Republic         | 13% |\n",
       "| Denmark                | 7%  |\n",
       "| ... | ... |\n",
       "| San Marino     | 0%  |\n",
       "| Serbia         | 9%  |\n",
       "| Slovakia       | 7%  |\n",
       "| Slovenia       | 3%  |\n",
       "| Spain          | 58% |\n",
       "| Sweden         | 12% |\n",
       "| Switzerland    | 10% |\n",
       "| Ukraine        | 53% |\n",
       "| United Kingdom | 79% |\n",
       "| Vatican City   | 0%  |\n",
       "\n"
      ],
      "text/plain": [
       "    name                   percentage\n",
       "1   Albania                3%        \n",
       "2   Andorra                0%        \n",
       "3   Austria                11%       \n",
       "4   Belarus                12%       \n",
       "5   Belgium                14%       \n",
       "6   Bosnia and Herzegovina 5%        \n",
       "7   Bulgaria               9%        \n",
       "8   Croatia                5%        \n",
       "9   Czech Republic         13%       \n",
       "10  Denmark                7%        \n",
       "... ...                    ...       \n",
       "35  San Marino             0%        \n",
       "36  Serbia                 9%        \n",
       "37  Slovakia               7%        \n",
       "38  Slovenia               3%        \n",
       "39  Spain                  58%       \n",
       "40  Sweden                 12%       \n",
       "41  Switzerland            10%       \n",
       "42  Ukraine                53%       \n",
       "43  United Kingdom         79%       \n",
       "44  Vatican City           0%        "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>% \n",
    "    filter(name=='Germany') %>% \n",
    "    select(population) %>%\n",
    "    pull\n",
    "world %>% \n",
    "    filter(continent=='Europe') %>% \n",
    "    mutate(percentage=sprintf('%0.0f%%', 100*round(population/bm, 2))) %>% \n",
    "    select(name, percentage)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Bigger than every country in Europe\n",
    "\n",
    "Which countries have a GDP greater than every country in Europe? [Give the name only.] (Some countries may have NULL gdp values)\n",
    "\n",
    "We can refer to values in the outer SELECT within the inner SELECT. We can name the tables so that we can tell the difference between the inner and outer versions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 3 × 1</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>China        </td></tr>\n",
       "\t<tr><td>Japan        </td></tr>\n",
       "\t<tr><td>United States</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 3 × 1\n",
       "\\begin{tabular}{l}\n",
       " name\\\\\n",
       " <chr>\\\\\n",
       "\\hline\n",
       "\t China        \\\\\n",
       "\t Japan        \\\\\n",
       "\t United States\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 3 × 1\n",
       "\n",
       "| name &lt;chr&gt; |\n",
       "|---|\n",
       "| China         |\n",
       "| Japan         |\n",
       "| United States |\n",
       "\n"
      ],
      "text/plain": [
       "  name         \n",
       "1 China        \n",
       "2 Japan        \n",
       "3 United States"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>% \n",
    "    filter(continent=='Europe' & ! is.na(gdp)) %>% \n",
    "    select(gdp) %>% \n",
    "    pull\n",
    "world %>% \n",
    "    filter(gdp %>% (function(x) {\n",
    "        vapply(x, function(i) all(i>bm), logical(1L))\n",
    "    })) %>% \n",
    "    select(name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Largest in each continent\n",
    "\n",
    "**Find the largest country (by area) in each continent, show the continent, the name and the area:**\n",
    "\n",
    "```sql\n",
    "SELECT continent, name, population FROM world x\n",
    "  WHERE population >= ALL\n",
    "    (SELECT population FROM world y\n",
    "        WHERE y.continent=x.continent\n",
    "          AND population>0)\n",
    "```\n",
    "\n",
    "> __The above example is known as a correlated or synchronized sub-query.__   \n",
    "> \n",
    "> Using correlated subqueries\n",
    "> A correlated subquery works like a nested loop: the subquery only has access to rows related to a single > record at a time in the outer query. The technique relies on table aliases to identify two different uses of the same table, one in the outer query and the other in the subquery.\n",
    "> \n",
    "> One way to interpret the line in the **WHERE** clause that references the two table is _“… where the correlated values are the same”._\n",
    "> \n",
    "> In the example provided, you would say _“select the country details from world where the population is greater than or equal to the population of all countries where the continent is the same”._"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A grouped_df: 8 × 3</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>continent</th><th scope=col>name</th><th scope=col>area</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;dbl&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Africa       </td><td>Algeria   </td><td> 2381741</td></tr>\n",
       "\t<tr><td>Oceania      </td><td>Australia </td><td> 7692024</td></tr>\n",
       "\t<tr><td>South America</td><td>Brazil    </td><td> 8515767</td></tr>\n",
       "\t<tr><td>North America</td><td>Canada    </td><td> 9984670</td></tr>\n",
       "\t<tr><td>Asia         </td><td>China     </td><td> 9596961</td></tr>\n",
       "\t<tr><td>Caribbean    </td><td>Cuba      </td><td>  109884</td></tr>\n",
       "\t<tr><td>Europe       </td><td>Kazakhstan</td><td> 2724900</td></tr>\n",
       "\t<tr><td>Eurasia      </td><td>Russia    </td><td>17125242</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A grouped\\_df: 8 × 3\n",
       "\\begin{tabular}{lll}\n",
       " continent & name & area\\\\\n",
       " <chr> & <chr> & <dbl>\\\\\n",
       "\\hline\n",
       "\t Africa        & Algeria    &  2381741\\\\\n",
       "\t Oceania       & Australia  &  7692024\\\\\n",
       "\t South America & Brazil     &  8515767\\\\\n",
       "\t North America & Canada     &  9984670\\\\\n",
       "\t Asia          & China      &  9596961\\\\\n",
       "\t Caribbean     & Cuba       &   109884\\\\\n",
       "\t Europe        & Kazakhstan &  2724900\\\\\n",
       "\t Eurasia       & Russia     & 17125242\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A grouped_df: 8 × 3\n",
       "\n",
       "| continent &lt;chr&gt; | name &lt;chr&gt; | area &lt;dbl&gt; |\n",
       "|---|---|---|\n",
       "| Africa        | Algeria    |  2381741 |\n",
       "| Oceania       | Australia  |  7692024 |\n",
       "| South America | Brazil     |  8515767 |\n",
       "| North America | Canada     |  9984670 |\n",
       "| Asia          | China      |  9596961 |\n",
       "| Caribbean     | Cuba       |   109884 |\n",
       "| Europe        | Kazakhstan |  2724900 |\n",
       "| Eurasia       | Russia     | 17125242 |\n",
       "\n"
      ],
      "text/plain": [
       "  continent     name       area    \n",
       "1 Africa        Algeria     2381741\n",
       "2 Oceania       Australia   7692024\n",
       "3 South America Brazil      8515767\n",
       "4 North America Canada      9984670\n",
       "5 Asia          China       9596961\n",
       "6 Caribbean     Cuba         109884\n",
       "7 Europe        Kazakhstan  2724900\n",
       "8 Eurasia       Russia     17125242"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "world %>% \n",
    "    group_by(continent) %>% \n",
    "    top_n(1, area) %>% \n",
    "    select(continent, name, area)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. First country of each continent (alphabetically)\n",
    "\n",
    "**List each continent and the name of the country that comes first alphabetically.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A grouped_df: 8 × 2</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>continent</th><th scope=col>name</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Africa       </td><td>Algeria            </td></tr>\n",
       "\t<tr><td>Asia         </td><td>Afghanistan        </td></tr>\n",
       "\t<tr><td>Caribbean    </td><td>Antigua and Barbuda</td></tr>\n",
       "\t<tr><td>Eurasia      </td><td>Armenia            </td></tr>\n",
       "\t<tr><td>Europe       </td><td>Albania            </td></tr>\n",
       "\t<tr><td>North America</td><td>Belize             </td></tr>\n",
       "\t<tr><td>Oceania      </td><td>Australia          </td></tr>\n",
       "\t<tr><td>South America</td><td>Argentina          </td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A grouped\\_df: 8 × 2\n",
       "\\begin{tabular}{ll}\n",
       " continent & name\\\\\n",
       " <chr> & <chr>\\\\\n",
       "\\hline\n",
       "\t Africa        & Algeria            \\\\\n",
       "\t Asia          & Afghanistan        \\\\\n",
       "\t Caribbean     & Antigua and Barbuda\\\\\n",
       "\t Eurasia       & Armenia            \\\\\n",
       "\t Europe        & Albania            \\\\\n",
       "\t North America & Belize             \\\\\n",
       "\t Oceania       & Australia          \\\\\n",
       "\t South America & Argentina          \\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A grouped_df: 8 × 2\n",
       "\n",
       "| continent &lt;chr&gt; | name &lt;chr&gt; |\n",
       "|---|---|\n",
       "| Africa        | Algeria             |\n",
       "| Asia          | Afghanistan         |\n",
       "| Caribbean     | Antigua and Barbuda |\n",
       "| Eurasia       | Armenia             |\n",
       "| Europe        | Albania             |\n",
       "| North America | Belize              |\n",
       "| Oceania       | Australia           |\n",
       "| South America | Argentina           |\n",
       "\n"
      ],
      "text/plain": [
       "  continent     name               \n",
       "1 Africa        Algeria            \n",
       "2 Asia          Afghanistan        \n",
       "3 Caribbean     Antigua and Barbuda\n",
       "4 Eurasia       Armenia            \n",
       "5 Europe        Albania            \n",
       "6 North America Belize             \n",
       "7 Oceania       Australia          \n",
       "8 South America Argentina          "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "world %>% \n",
    "    group_by(continent) %>% \n",
    "    slice(1) %>% \n",
    "    select(continent, name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. Difficult Questions That Utilize Techniques Not Covered In Prior Sections\n",
    "\n",
    "**Find the continents where all countries have a population <= 25000000. Then find the names of the countries associated with these continents. Show name, continent and population.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A data.frame: 25 × 3</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th><th scope=col>continent</th><th scope=col>population</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;dbl&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Antigua and Barbuda</td><td>Caribbean</td><td>   86295</td></tr>\n",
       "\t<tr><td>Australia          </td><td>Oceania  </td><td>23545500</td></tr>\n",
       "\t<tr><td>Bahamas            </td><td>Caribbean</td><td>  351461</td></tr>\n",
       "\t<tr><td>Barbados           </td><td>Caribbean</td><td>  285000</td></tr>\n",
       "\t<tr><td>Cuba               </td><td>Caribbean</td><td>11167325</td></tr>\n",
       "\t<tr><td>Dominica           </td><td>Caribbean</td><td>   71293</td></tr>\n",
       "\t<tr><td>Dominican Republic </td><td>Caribbean</td><td> 9445281</td></tr>\n",
       "\t<tr><td>Fiji               </td><td>Oceania  </td><td>  858038</td></tr>\n",
       "\t<tr><td>Grenada            </td><td>Caribbean</td><td>  103328</td></tr>\n",
       "\t<tr><td>Haiti              </td><td>Caribbean</td><td>10413211</td></tr>\n",
       "\t<tr><td>...</td><td>...</td><td>...</td></tr>\n",
       "\t<tr><td>New Zealand        </td><td>Oceania  </td><td>4538520</td></tr>\n",
       "\t<tr><td>Palau              </td><td>Oceania  </td><td>  20901</td></tr>\n",
       "\t<tr><td>Papua New Guinea   </td><td>Oceania  </td><td>7398500</td></tr>\n",
       "\t<tr><td>Saint Lucia        </td><td>Caribbean</td><td> 180000</td></tr>\n",
       "\t<tr><td>Samoa              </td><td>Oceania  </td><td> 187820</td></tr>\n",
       "\t<tr><td>Solomon Islands    </td><td>Oceania  </td><td> 581344</td></tr>\n",
       "\t<tr><td>Tonga              </td><td>Oceania  </td><td> 103036</td></tr>\n",
       "\t<tr><td>Trinidad and Tobago</td><td>Caribbean</td><td>1328019</td></tr>\n",
       "\t<tr><td>Tuvalu             </td><td>Oceania  </td><td>  11323</td></tr>\n",
       "\t<tr><td>Vanuatu            </td><td>Oceania  </td><td> 264652</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A data.frame: 25 × 3\n",
       "\\begin{tabular}{lll}\n",
       " name & continent & population\\\\\n",
       " <chr> & <chr> & <dbl>\\\\\n",
       "\\hline\n",
       "\t Antigua and Barbuda & Caribbean &    86295\\\\\n",
       "\t Australia           & Oceania   & 23545500\\\\\n",
       "\t Bahamas             & Caribbean &   351461\\\\\n",
       "\t Barbados            & Caribbean &   285000\\\\\n",
       "\t Cuba                & Caribbean & 11167325\\\\\n",
       "\t Dominica            & Caribbean &    71293\\\\\n",
       "\t Dominican Republic  & Caribbean &  9445281\\\\\n",
       "\t Fiji                & Oceania   &   858038\\\\\n",
       "\t Grenada             & Caribbean &   103328\\\\\n",
       "\t Haiti               & Caribbean & 10413211\\\\\n",
       "\t ... & ... & ...\\\\\n",
       "\t New Zealand         & Oceania   & 4538520\\\\\n",
       "\t Palau               & Oceania   &   20901\\\\\n",
       "\t Papua New Guinea    & Oceania   & 7398500\\\\\n",
       "\t Saint Lucia         & Caribbean &  180000\\\\\n",
       "\t Samoa               & Oceania   &  187820\\\\\n",
       "\t Solomon Islands     & Oceania   &  581344\\\\\n",
       "\t Tonga               & Oceania   &  103036\\\\\n",
       "\t Trinidad and Tobago & Caribbean & 1328019\\\\\n",
       "\t Tuvalu              & Oceania   &   11323\\\\\n",
       "\t Vanuatu             & Oceania   &  264652\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A data.frame: 25 × 3\n",
       "\n",
       "| name &lt;chr&gt; | continent &lt;chr&gt; | population &lt;dbl&gt; |\n",
       "|---|---|---|\n",
       "| Antigua and Barbuda | Caribbean |    86295 |\n",
       "| Australia           | Oceania   | 23545500 |\n",
       "| Bahamas             | Caribbean |   351461 |\n",
       "| Barbados            | Caribbean |   285000 |\n",
       "| Cuba                | Caribbean | 11167325 |\n",
       "| Dominica            | Caribbean |    71293 |\n",
       "| Dominican Republic  | Caribbean |  9445281 |\n",
       "| Fiji                | Oceania   |   858038 |\n",
       "| Grenada             | Caribbean |   103328 |\n",
       "| Haiti               | Caribbean | 10413211 |\n",
       "| ... | ... | ... |\n",
       "| New Zealand         | Oceania   | 4538520 |\n",
       "| Palau               | Oceania   |   20901 |\n",
       "| Papua New Guinea    | Oceania   | 7398500 |\n",
       "| Saint Lucia         | Caribbean |  180000 |\n",
       "| Samoa               | Oceania   |  187820 |\n",
       "| Solomon Islands     | Oceania   |  581344 |\n",
       "| Tonga               | Oceania   |  103036 |\n",
       "| Trinidad and Tobago | Caribbean | 1328019 |\n",
       "| Tuvalu              | Oceania   |   11323 |\n",
       "| Vanuatu             | Oceania   |  264652 |\n",
       "\n"
      ],
      "text/plain": [
       "    name                continent population\n",
       "1   Antigua and Barbuda Caribbean    86295  \n",
       "2   Australia           Oceania   23545500  \n",
       "3   Bahamas             Caribbean   351461  \n",
       "4   Barbados            Caribbean   285000  \n",
       "5   Cuba                Caribbean 11167325  \n",
       "6   Dominica            Caribbean    71293  \n",
       "7   Dominican Republic  Caribbean  9445281  \n",
       "8   Fiji                Oceania     858038  \n",
       "9   Grenada             Caribbean   103328  \n",
       "10  Haiti               Caribbean 10413211  \n",
       "... ...                 ...       ...       \n",
       "16  New Zealand         Oceania   4538520   \n",
       "17  Palau               Oceania     20901   \n",
       "18  Papua New Guinea    Oceania   7398500   \n",
       "19  Saint Lucia         Caribbean  180000   \n",
       "20  Samoa               Oceania    187820   \n",
       "21  Solomon Islands     Oceania    581344   \n",
       "22  Tonga               Oceania    103036   \n",
       "23  Trinidad and Tobago Caribbean 1328019   \n",
       "24  Tuvalu              Oceania     11323   \n",
       "25  Vanuatu             Oceania    264652   "
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "bm <- world %>% \n",
    "    group_by(continent) %>% \n",
    "    mutate(flg=population<=25000000) %>% \n",
    "    filter(sum(flg)==n()) %>% \n",
    "    pull(continent) %>% \n",
    "    unique\n",
    "world %>% \n",
    "    filter(continent %in% bm) %>% \n",
    "    select(name, continent, population)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10.\n",
    "\n",
    "**Some countries have populations more than three times that of any of their neighbours (in the same continent). Give the countries and continents.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<table>\n",
       "<caption>A grouped_df: 3 × 2</caption>\n",
       "<thead>\n",
       "\t<tr><th scope=col>name</th><th scope=col>continent</th></tr>\n",
       "\t<tr><th scope=col>&lt;chr&gt;</th><th scope=col>&lt;chr&gt;</th></tr>\n",
       "</thead>\n",
       "<tbody>\n",
       "\t<tr><td>Russia   </td><td>Eurasia      </td></tr>\n",
       "\t<tr><td>Australia</td><td>Oceania      </td></tr>\n",
       "\t<tr><td>Brazil   </td><td>South America</td></tr>\n",
       "</tbody>\n",
       "</table>\n"
      ],
      "text/latex": [
       "A grouped\\_df: 3 × 2\n",
       "\\begin{tabular}{ll}\n",
       " name & continent\\\\\n",
       " <chr> & <chr>\\\\\n",
       "\\hline\n",
       "\t Russia    & Eurasia      \\\\\n",
       "\t Australia & Oceania      \\\\\n",
       "\t Brazil    & South America\\\\\n",
       "\\end{tabular}\n"
      ],
      "text/markdown": [
       "\n",
       "A grouped_df: 3 × 2\n",
       "\n",
       "| name &lt;chr&gt; | continent &lt;chr&gt; |\n",
       "|---|---|\n",
       "| Russia    | Eurasia       |\n",
       "| Australia | Oceania       |\n",
       "| Brazil    | South America |\n",
       "\n"
      ],
      "text/plain": [
       "  name      continent    \n",
       "1 Russia    Eurasia      \n",
       "2 Australia Oceania      \n",
       "3 Brazil    South America"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# self full join other countries with population*3\n",
    "# filter out population > other population*3\n",
    "# count the countries, search for n=(country number on the continent)-1\n",
    "world %>% \n",
    "    select(name, continent, population) %>% \n",
    "    full_join(world %>% \n",
    "              mutate(popl3=population*3) %>% \n",
    "              select(continent, name, popl3), \n",
    "              by='continent', \n",
    "              suffix=c('', '.y')) %>% \n",
    "    filter(name != name.y, population > popl3) %>%\n",
    "    group_by(continent, name) %>% \n",
    "    summarise(n=n()) %>%\n",
    "    inner_join(world %>% \n",
    "               group_by(continent) %>%\n",
    "               summarise(n=n()-1), \n",
    "               by='continent', \n",
    "               suffix=c('', '.y')) %>%\n",
    "    filter(n==n.y) %>% \n",
    "    select(name, continent)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "dbDisconnect(con)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "4.0.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
